const resourceService = require('@/services/resource.service')
const JsonResult = require('@/utils/httpResponse.util')

class ResourceController {
  async create (req, response) {
    const body = req.body
    try {
      const data = await resourceService.create(body)
      if (data?.errorMessage) {
        return JsonResult.fail({ req, response, message: data.errorMessage })
      }
      JsonResult.success({
        req,
        response,
        message: '新增成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '新增失败' })
    }
  }

  async find (req, response) {
    try {
      const { type, searchKeywords } = req.query
      const data = await resourceService.find(type, searchKeywords)
      JsonResult.success({
        req,
        response,
        data,
        message: '查询成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '查询失败' })
    }
  }

  async delete (req, response) {
    const id = req.query.id
    try {
      const data = await resourceService.recursiveDelete(id)
      if (data?.errorMessage) {
        return JsonResult.fail({ req, response, message: data.errorMessage })
      }
      JsonResult.success({
        req,
        response,
        message: '删除成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '删除失败' })
    }
  }

  async update (req, response) {
    const { id, ...attrs } = req.body
    try {
      const data = await resourceService.update(id, attrs)
      if (data?.errorMessage) {
        return JsonResult.fail({ req, response, message: data.errorMessage })
      }
      JsonResult.success({
        req,
        response,
        message: '更新成功'
      })
    } catch (error) {
      JsonResult.fail({ req, response, error, message: '更新失败' })
    }
  }
}

module.exports = new ResourceController()
